package com.ns.sbs.oauth.role4permission.controller;

import com.ns.core.annotations.ReqLog;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.current.config.SysConst;
import com.ns.core.utils.StpUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.core.utils.sg.ResultOk;
import com.ns.sbs.oauth.acc.entry.Acc2Server;
import com.ns.sbs.oauth.acc.service.IAcc2ServerService;
import com.ns.sbs.oauth.cur.AuthTreeVO;
import com.ns.sbs.oauth.menu.service.IMenuService;
import com.ns.sbs.oauth.rent.service.IRentService;
import com.ns.sbs.oauth.role.service.IRoleService;
import com.ns.sbs.oauth.role.vo.RoleEntryVO;
import com.ns.sbs.oauth.role4permission.bo.RolePermissionBO;
import com.ns.sbs.oauth.role4permission.service.RolePermissionServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 角色与权限操作
 *
 * @author lw
 */
@RestController
@RequestMapping("/role/permission/")
@RequiredArgsConstructor
@CrossOrigin
public class RolePermissionController {

    private final RolePermissionServiceImpl rolePermissionService;

    private final IMenuService menuService;

    private final IRoleService roleService;

    private final IRentService rentService;

    private final IAcc2ServerService acc2ServerService;

    /**
     * 获取角色所在租户已分配当前服务菜单
     *
     * @param roleId 角色id
     */
    @GetMapping("tree")
    @ReqLog(module = "角色与权限模块", name = "菜单树")
    public ResultOk getMenuTreeByRoleId(Long roleId) {
        AuthTreeVO tree = new AuthTreeVO();
        // 确定租户
        RoleEntryVO roleEntryVO = roleService.getById(roleId);
        if (Objects.nonNull(roleEntryVO)) {
            // 服务id
            Long sid = roleEntryVO.getSid();
            // 租户id
            Long rid = roleEntryVO.getRid();
            // 租户权限菜单
            Set<Long> pms = new HashSet<>();
            List<List<String>> permissions = rentService.getRentPermission(rid);
            if (CollectionUtils.isEmpty(permissions)) {
                throw new ResultError("未知权限异常");
            }
            for (List<String> permission : permissions) {
                if (permission.contains(String.valueOf(sid))) {
                    for (int i = 1; i < permission.size(); i++) {
                        pms.add(Long.parseLong(permission.get(i)));
                    }
                }
            }

            if (!CollectionUtils.isEmpty(pms)) {
                // 查询菜单
                tree.setBt(menuService.getMenuByMid(new ArrayList<>(pms)));
                // 已选菜单
                List<Long> holdMenus = rolePermissionService.getCodeByRoleId(roleId);
                tree.setPms(holdMenus.stream().map(String::valueOf).collect(toList()));
            }
        }
        return ResultOk.getSuccessData(tree);
    }

    /**
     * 拉取菜单id列表  根据当前用户roleId
     */
    @GetMapping("getCodeByCurrRid")
    @ReqLog(module = "角色与权限模块", name = "拉取菜单id列表  根据当前用户roleId")
    public ResultOk getCodeByCurrRid() {
        // 获取用户角色
        Acc2Server acc2Server = acc2ServerService.getByAccAndSid(Objects.requireNonNull(StpUtil.getCurUser()).getId(), StpUtil.getSid());
        if (Objects.isNull(acc2Server)) {
            throw new ResultError("该用户赞绑定角色,请联系管理员！");
        }
        return ResultOk.getSuccessData(rolePermissionService.getCodeByRoleId(acc2Server.getRoleId()));
    }

    /**
     * 修改指定角色的拥有的权限
     *
     * @param bo 角色权限
     * @return ResultOk
     */
    @PostMapping("updateCodeByRid")
    @ReqLog(module = "角色与权限模块", name = "修改指定角色的拥有的权限")
    @CacheEvict(cacheNames = SysConst.ROLE_DICT, key = "#bo.roleId")
    public ResultOk updateCodeByRid(@RequestBody RolePermissionBO bo) {
        List<String> list = Arrays.stream(bo.getCodes().split(SymbolsMark.COMMA)).toList();
        int line = rolePermissionService.updateRoleMenu(bo.getRoleId(), list);
        return ResultOk.getSuccessData(line);
    }

}
